import React from "react";
import {FormikProps, getIn} from "formik";
import InputIcon from "@src/components/inputIcon";
import "./index.scss"
import {motion, AnimatePresence} from 'framer-motion';
// 定义 FormInputIcon 的 Props 类型
export type FormInputIconProps<T> = {
    Icon: React.ReactNode;
    name: keyof T; // 表单字段的名称
    formik: FormikProps<T>;
} & React.InputHTMLAttributes<HTMLInputElement>;

// FormInputIcon 组件
export default function FormInputIcon<T>({Icon, name, formik, ...props}: FormInputIconProps<T>) {
    // 确保 name 是字符串
    const error = getIn(formik.errors, name.toString());
    const fieldProps = formik.getFieldProps(name.toString());
    const touched = getIn(formik.touched, name.toString());
    const hasError = touched && error;
    return (
        <div className="form-input">
            <InputIcon
                Icon={Icon}
                {...fieldProps}
                {...props}
            />

            <AnimatePresence mode="wait">
                {hasError && (
                    <motion.div
                        className="error-message"
                        initial={{opacity: 0}} // 初始状态
                        animate={{opacity: 1}} // 进入动画
                        exit={{opacity: 0}} // 退出动画
                        transition={{duration: 0.3}} // 动画持续时间
                    >
                        {error}
                    </motion.div>
                )}
            </AnimatePresence>

            {/*{hasError && <div className="error-message">{error}</div>}*/}
        </div>
    );
}